<template>
  <div>
    
    <div class="common-layout" style=" margin: 0 30%;">
     
      <div>
        <p >角色分配菜单</p>
        <el-container>
          <el-aside width="200px">
            角色
            <!-- 使用 el-tree 组件展示树形数据 -->
            <el-tree :data="RoleModel" :highlight-current="true" ref="treeRef" :props="treePropsRole" node-key="roleId"
              @node-click="handleNodeClickRole">
            </el-tree>
            <!-- 显示点击节点的 roleId -->
            <!-- <div v-if="AddModel.roleId">你点击的节点的 roleId 是: {{ AddModel.roleId }}</div> -->
          </el-aside>
          <el-aside width="200px">
            <div>
              <!-- 使用 el-tree 组件 -->
              <el-tree :data="treeData" :default-checked-keys="AddModel.menuIds" show-checkbox node-key="menuId"
                :props="defaultPropsMenu" @check-change="handleCheckChange" ref="treeRef"
                :default-expand-all="true"></el-tree>
              <!-- 显示选中的 menuId -->
              <!-- <div>选中的 menuId: {{ AddModel.menuId }}</div> -->
            </div>
          </el-aside>
        </el-container>
      </div>
      <div>
        <el-button style="margin-left: 370px;" type="primary" @click="AddRoleMenu">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
//#region import
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import { compile, computed, nextTick, onMounted, reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from '@/stores/counter';
import DepData from '@/stores/departmentData'
import axios from 'axios';
import { ElTree } from 'element-plus';
import type { AnyColumn } from 'element-plus/es/components/table-v2/src/common.mjs';
//pini保存
const store = useCounterStore();
//跳转
const router = useRouter();

//#endregion

//#region  获取角色数据(id,名称)
//查询角色所需数据
const page=reactive({
    pageindex:1,
    pagesize:100,
    totalcount:0,
    totalpage:0,
})
//获取角色的数据
const RoleModel = ref([])
//获取角色数据(id, 名称)
const GetRole = () => {
  axios({
    url:'http://localhost:5284/api/Role/QueryRole',
    method:'get',
    params:{
      Pageindex:page.pageindex,
      Pagesize:page.pagesize
    }
  })
  .then(res => {
    RoleModel.value = res.data.list
    console.log(RoleModel.value, "角色名称")
  })
}

// 定义树的属性配置
const treePropsRole: any = ref({
  label: 'roleName', // 指定节点的标签显示字段为 roleName
  children: [] // 指定子节点字段为 children
});






// 处理节点点击事件(通过roleId 查询 菜单数据实现反填)
const handleNodeClickRole = (data: any) => {
  //清空节点
  AddModel.menuIds = [];
  AddModel.roleId = data.roleId;
  axios({
    url:'http://localhost:5284/api/Menu/GetMenuNameFanTian',
    method:'get',
    params:{
      RoleId:data.roleId
    }
  }).then(res => {
    AddModel.menuIds = res.data.data.map((item: any) => item.menuId)
    console.log(res.data.data, '反填菜单名称res')
    console.log(AddModel.menuIds, '反填菜单名称')
    nextTick()
    // 强制更新 el-tree 的选中状态
    treeRef.value.setCheckedKeys(AddModel.menuIds);
  })
};

//#endregion


//#region  获取菜单数据(id,名称)

//获取菜单的数据
const MenuModel = ref([])
// 存储树形结构的数据
const treeData = ref([]);
//获取菜单数据(id, 名称)
const GetMenu = () => {
  axios({
    url:'http://localhost:5284/api/Menu/QueryMenuName',
    method:'get',
  })
  .then(res => {
    MenuModel.value = res.data.list
    console.log(MenuModel.value, "赋值MenuModel.value")
    console.log(res.data.data, "获取res.data.data")
    treeData.value = convertToTree(MenuModel.value)
    console.log(treeData.value, "获取树形菜单")
  })
}

// 将普通数组转换为树形结构
const convertToTree = (data: any) => {
  const tree: any = [];
  const map: any = {};

  // 先将每个节点存储到 map 中
  data.forEach((item: any) => {
    map[item.menuId] = { ...item, children: [] };
  });

  // 再根据 parentId 构建树形结构
  data.forEach((item: any) => {
    if (item.pid === 0) {
      tree.push(map[item.menuId]);
    } else {
      const parent = map[item.pid];
      if (parent) {
        parent.children.push(map[item.menuId]);
      }
    }
  });
  return tree;
};

// 获取 el-tree 组件的引用
const treeRef = ref<InstanceType<typeof ElTree>>();

// 定义 tree 组件的属性配置
const defaultPropsMenu = {
  children: 'children',
  label: 'menuName'
};

// 存储选中节点的 id 数组
const checkedIds: any = ref([]);

// 处理节点选中状态变化的事件
// const handleCheckChange = () => {
//   // 获取所有选中节点的 id
//   const allCheckedKeys = treeRef.value?.getCheckedKeys() || [];
//   // 获取所有半选中节点的 id
//   const allHalfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || [];
//   // 合并选中和半选中节点的 id
//   AddModel.menuId = [...allCheckedKeys];
//   console.log(AddModel.menuId)
// };

//获取菜单多选值
const handleCheckChange = () => {
  AddModel.menuIds = treeRef.value?.getCheckedKeys() || [];
  console.log(AddModel.menuIds, '获取单个选中值')
};


const AddModel: any = reactive({
  "roleId": "",
  "menuIds": []
})


//#endregion

//#region 添加


const AddRoleMenu = () => {
  if (AddModel.roleId == "") {
    ElMessage.error("请选择角色")
    return;
  }
  console.log(AddModel.menuIds)
  console.log(AddModel.roleId)
  axios({
    url:"http://localhost:5272/api/RoleMenu/AddRoleMenu",
    method:'post',
    data:AddModel
  })
  .then(res => {
    if (res.data.code == 101) {
      ElMessage.success("操作成功")
    }
  })
}

//#endregion



onMounted(() => {
  GetRole()
  GetMenu()
})





</script>

<style scoped></style>